package com.travel.service.impl.Travel;

import com.github.pagehelper.PageHelper;
import com.travel.exception.ResourceNotFoundException;
import com.travel.exception.UnauthorizedException;
import com.travel.mapper.content.CommentMapper;
import com.travel.mapper.order.BookingMapper;
import com.travel.mapper.service.ServiceMapper;
import com.travel.model.dto.comment.CommentRequest;
import com.travel.model.dto.comment.RatingStats;
import com.travel.model.dto.service.AuditDTO;
import com.travel.model.dto.service.BookingRequest;
import com.travel.model.dto.service.ServiceDTO;
import com.travel.model.entity.content.Comment;
import com.travel.model.entity.service.Booking;
import com.travel.model.entity.service.Service;
import com.travel.model.enums.BookingStatus;
import com.travel.service.Service.TravelService;
import com.travel.service.Service.UserService;
import com.travel.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
//旅游服务实现类 获取所有服务 获取特定城市服务 获取特定服务 创建服务 更新服务 删除服务 搜索服务 添加评论 获取评论 获取评分统计
@org.springframework.stereotype.Service
@RequiredArgsConstructor
public class TravelServiceImpl implements TravelService {

    private final ServiceMapper serviceMapper;
    private final BookingMapper bookingMapper;
    private final UserService userService;
    private final CommentMapper commentMapper;

    @Override
    public Page<ServiceDTO> getServices(String city, String type, Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Service> services;
        if (type != null && !type.isEmpty()) {
            services = serviceMapper.findByCityAndType(city, type);
        } else {
            services = serviceMapper.findByCity(city);
        }
        List<ServiceDTO> dtos = services.stream()
            .map(serviceMapper::toDTO)
            .collect(Collectors.toList());
        return new PageImpl<>(dtos);
    }

    @Override
    public List<ServiceDTO> getUserServices(Long userId) {
        if (userId == null) {
            userId = SecurityUtils.getCurrentUserId();
        }
        return serviceMapper.findByUserId(userId)
            .stream()
            .map(serviceMapper::toDTO)
            .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public ServiceDTO createService(ServiceDTO serviceDTO) {
        Service service = serviceMapper.toEntity(serviceDTO);
        
        // 设置创建者ID
        service.setUserId(SecurityUtils.getCurrentUserId());
        
        // 设置默认值
        service.setStatus(1);
        service.setCreatedTime(LocalDateTime.now());
        service.setUpdatedTime(LocalDateTime.now());
        
        // 设置默认图片
        if (org.springframework.util.ObjectUtils.isEmpty(service.getImageUrl())) {
            service.setImageUrl("http://pic.maxtral.fun/Onedrive/2024/12/18/default-service.jpg");
        }
        
        serviceMapper.save(service);
        return serviceMapper.toDTO(service);
    }

    @Override
    @Transactional
    public ServiceDTO updateService(Long id, ServiceDTO serviceDTO) {
        Service service = serviceMapper.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("服务不存在"));
        
        // 检查权限
        if (!service.getUserId().equals(SecurityUtils.getCurrentUserId())) {
            throw new UnauthorizedException("您没有权限修改此服务");
        }
        
        // 更新字段
        serviceMapper.updateEntity(serviceDTO, service);
        service.setUpdatedTime(LocalDateTime.now());
        
        serviceMapper.update(service);
        return serviceMapper.toDTO(service);
    }

    @Override
    @Transactional
    public void deleteService(Long id) {
        Service service = serviceMapper.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("服务不存在"));
        serviceMapper.delete(service);
    }

    @Override
    @Transactional
    public Booking createBooking(BookingRequest request) {
        Service service = serviceMapper.findById(request.getServiceId())
                .orElseThrow(() -> new ResourceNotFoundException("服务不存在"));

        Booking booking = new Booking();
        booking.setUserId(SecurityUtils.getCurrentUserId());
        booking.setServiceId(service.getId());
        booking.setBookingDate(request.getBookingDate());
        booking.setStatus(BookingStatus.PENDING);
        booking.setAmount(service.getPrice());
        booking.setCreatedTime(LocalDateTime.now());
        booking.setUpdatedTime(LocalDateTime.now());
        
        bookingMapper.save(booking);
        return booking;
    }

    @Override
    public List<Comment> getComments(Long serviceId) {
        return commentMapper.findByTargetAndStatus(serviceId, Comment.TargetType.SERVICE, 1);
    }

    @Override
    @Transactional
    public void deleteComment(Long commentId, Long userId) {
        Comment comment = commentMapper.findById(commentId)
            .orElseThrow(() -> new ResourceNotFoundException("评论不存在"));
        
        if (!comment.getUserId().equals(userId)) {
            throw new UnauthorizedException("您没有权限删除此评论");
        }
        
        comment.setStatus(0);
        commentMapper.update(comment);
    }

    @Override
    public Page<Booking> getUserBookings(Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Booking> bookings = bookingMapper.findByUserId(SecurityUtils.getCurrentUserId());
        return new PageImpl<>(bookings);
    }

    @Override
    public Page<ServiceDTO> getAllServices(Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Service> services = serviceMapper.findAll();
        List<ServiceDTO> dtos = services.stream()
            .map(serviceMapper::toDTO)
            .collect(Collectors.toList());
        return new PageImpl<>(dtos);
    }

    @Override
    @Transactional
    public void updateServiceStatus(Long id, Integer status) {
        Service service = serviceMapper.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("服务不存在"));
        service.setStatus(status);
        service.setUpdatedTime(LocalDateTime.now());
        serviceMapper.update(service);
    }

    @Override
    public void auditService(Long id, AuditDTO auditDTO) {
        updateServiceStatus(id, auditDTO.getStatus());
    }

    @Override
    @Transactional
    public Comment addComment(Long serviceId, CommentRequest request) {
        Service service = serviceMapper.findById(serviceId)
            .orElseThrow(() -> new ResourceNotFoundException("服务不存在"));
        
        Comment comment = new Comment();
        comment.setContent(request.getContent());
        comment.setRating(request.getRating());
        comment.setUserId(SecurityUtils.getCurrentUserId());
        comment.setTargetId(serviceId);
        comment.setTargetType(Comment.TargetType.SERVICE);
        comment.setCreatedTime(LocalDateTime.now());
        comment.setStatus(1);
        
        commentMapper.insert(comment);
        return comment;
    }

    @Override
    public ServiceDTO getServiceDetail(Long id) {
        Service service = serviceMapper.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("服务不存在"));
        return serviceMapper.toDTO(service);
    }

    @Override
    public List<ServiceDTO> getPublicServices() {
        return serviceMapper.findByStatus(1)
            .stream()
            .map(serviceMapper::toDTO)
            .collect(Collectors.toList());
    }

    @Override
    public RatingStats getServiceRating(Long serviceId) {
        RatingStats stats = new RatingStats();
        stats.setAverageRating(commentMapper.getAverageRating(
            serviceId, Comment.TargetType.SERVICE));
        stats.setCommentCount(commentMapper.getCommentCount(
            serviceId, Comment.TargetType.SERVICE));
        return stats;
    }

    private ServiceDTO convertToDTO(Service service) {
        ServiceDTO dto = new ServiceDTO();
        BeanUtils.copyProperties(service, dto);
        
        // 添加评分信息
        RatingStats stats = getServiceRating(service.getId());
        dto.setAverageRating(stats.getAverageRating());
        dto.setCommentCount(stats.getCommentCount());
        
        return dto;
    }
} 